//
//  GoodsTypeView.m
//  AddShoppingCartDemo
//
//  Created by Jim1024 on 2016/12/23.
//  Copyright © 2016年 Jim1024. All rights reserved.
//

#import "GoodsTypeView.h"

@implementation GoodsTypeView

- (instancetype)initWithFrame:(CGRect)frame datasource:(NSArray *)dataArr typeName:(NSString *)typeName {
    if (self = [super initWithFrame:frame]) {
        UILabel *titleLb = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 20)];
        titleLb.text = typeName;
        titleLb.textColor = [UIColor blackColor];
        titleLb.font = [UIFont systemFontOfSize:14];
        [self addSubview:titleLb];
        
        BOOL isLineReturn = NO;
        CGFloat upX = 10;
        CGFloat upY = 40;
        for (int i = 0; i < dataArr.count; i++) {
            NSString *str = [dataArr objectAtIndex:i];
            NSDictionary *attrDict = [NSDictionary dictionaryWithObject:[UIFont boldSystemFontOfSize:14] forKey:NSFontAttributeName];
            CGSize stringSize = [str sizeWithAttributes:attrDict];
            if (upX > (self.frame.size.width - 20 - stringSize.width - 35)) {
                isLineReturn = YES;
                upX = 10;
                upY += 30;
            }
            
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(upX, upY, stringSize.width + 30, 25);
            [btn setBackgroundColor:[UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1]];
            [btn setTitleColor:[UIColor blackColor] forState:0];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
            btn.titleLabel.font = [UIFont systemFontOfSize:13];
            [btn setTitle:str forState:0];
            btn.layer.cornerRadius = 8;
            [btn.layer setMasksToBounds:YES];
            
            [self addSubview:btn];
            btn.tag = 100 + i;
            [btn addTarget:self action:@selector(touchBtnBtn:) forControlEvents:UIControlEventTouchUpInside];
            
            upX += stringSize.width + 35;
        }
        
        upY += 30;
        UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(0, upY+10, self.frame.size.width, 0.5)];
        line.backgroundColor = [UIColor lightGrayColor];
        [self addSubview:line];
        
        self.viewHeight = upY + 11;
        self.seletIndex = -1;
    }
    return self;
}

- (void)touchBtnBtn:(UIButton *)btn {
    if (btn.selected == NO) {
        self.seletIndex = btn.tag - 100;
        btn.backgroundColor = [UIColor redColor];
    }else {
        self.seletIndex = -1;
        btn.selected = NO;
        btn.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1];
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(selectButtonIndex:)]) {
        [self.delegate selectButtonIndex:btn.tag - 100];
    }
}

@end
